<template>
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="750px"
      draggable
      @close="closeDialog"
      :close-on-click-modal="false"
      destroy-on-close
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        v-loading="loading1"
        :rules="rules"
        label-width="105px"
        style="display: flex; width: 98%"
      >
        <el-row>
          <!-- 工厂号-->
          <el-col :span="12">
            <el-form-item label="物料编号">
              <el-input
                v-model="formData.materialCode"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称">
              <el-input
                v-model="formData.materialName"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商编号">
              <el-input
                v-model="formData.partnerCode"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称">
              <el-input
                v-model="formData.partnerName"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卸货口">
              <el-input
                v-model="formData.dischargeHatchCode"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="要货日期" prop="demandDate">
              <el-date-picker
                :disabled="props.cellId != ''"
                v-model="formData.demandDate"
                :disabled-date="disabledDate"
                style="width: 100%"
                type="date"
                placeholder="请选择要货日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="要货数量" prop="demandQuantity">
              <el-input-number
                v-model="formData.demandQuantity"
                :min="1"
                :precision="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer v-if="!loading1">
        <div class="dialog-footer">
          <el-button type="primary" :loading="loading" @click="handleSubmit"
            >确 定</el-button
          >
          <el-button
            v-if="formData?.id"
            type="danger"
            :loading="loadingDelete"
            @click="deleteItem(props.cellId)"
            >删 除</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";

defineOptions({
  name: "SRMREQUIREGOODSADDDIALOG",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  cellId: {
    type: String,
    default: () => {
      return "";
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  beginDate: {
    type: String,
    default: () => {
      return "";
    },
  },
  endDate: {
    type: String,
    default: () => {
      return "";
    },
  },
});
const disabled = ref(false);
const loading1 = ref(true);
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    loading1.value = true;

    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

// 表单校验规则
const rules = reactive({
  plantId: [{ required: true, message: "未选择工厂", trigger: "change" }],
  partnerId: [{ required: true, message: "未选择供应商", trigger: "change" }],
  arriveDate: [
    {
      required: true,
      type: "date",
      message: "未选择到货日期",
      trigger: "change",
    },
  ],
  demandDate: [
    {
      required: true,
      message: "未选择要货日期",
      trigger: "change",
    },
  ],
  materialId: [{ required: true, message: "未选择物料", trigger: "blur" }],
  storageLocationName: [
    { required: true, message: "未选择要货地点", trigger: "change" },
  ],
  planQuantity: [
    { required: true, message: "未输入要货数量", trigger: "change" },
  ],
  dischargeHatchId: [
    { required: true, message: "未选择卸货口", trigger: "change" },
  ],
  purchasePlanNumber: [
    { required: true, message: "未选择采购协议", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  beginDate: [],
  endDate: [],
  filename: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  dischargeHatchId: "",
  dischargeHatchCode: "",
  dischargeHatchName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  // 物料需求ID
  demandId: props.id,
  // 需求日期
  demandDate: "",
  // 需求数量
  demandQuantity: 0,
  // 需求日期（格式化）
  demandDateShow: "",
  // 计划id
  planId: "",
});

// 如果有行id 说明是新增
watch(
  () => props.id,
  (newVal: any) => {
    if (newVal) {
      loading1.value = true;
      getSchedule(props.id);
    }
  }
);
// 如果有单元格id 说明是修改
watch(
  () => props.cellId,
  (newVal: any) => {
    if (newVal) {
      loading1.value = true;
      getCellList(newVal);
    }
  }
);

const getCellList = async (id) => {
  await request({
    url: `/srm/srmdemandschedule/getInfo/${id}`,
    method: "get",
  })
    .then((res) => {
      Object.assign(formData, { ...res.data });
      loading1.value = false;
    })
    .catch(() => {
      loading1.value = false;
    });
};

// 获取要货需求明细
const scheduleList = ref([]);
async function getSchedule(id1) {
  const data = await request({
    url: `/srm/srmmaterialdemand/get/${id1}`,
    method: "get",
  }).catch(() => {
    loading1.value = false;
  });
  scheduleList.value = data.data;
  const {
    plantId,
    plantCode,
    plantName,
    partnerId,
    partnerCode,
    partnerName,
    dischargeHatchId,
    dischargeHatchCode,
    dischargeHatchName,
    materialId,
    materialCode,
    materialName,
  } = data.data;
  Object.assign(formData, {
    plantId,
    plantCode,
    plantName,
    partnerId,
    partnerCode,
    partnerName,
    dischargeHatchId,
    dischargeHatchCode,
    dischargeHatchName,
    materialId,
    materialCode,
    materialName,
  });
  loading1.value = false;
}

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.dischargeHatchId = "";
  formData.dischargeHatchCode = "";
  formData.dischargeHatchName = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";

  formData.demandId = props.id;
  // 需求日期
  formData.demandDate = "";
  // 需求数量
  formData.demandQuantity = 0;
  // 需求日期（格式化）
  formData.demandDateShow = "";
  // 计划id
  formData.planId = "";
  disabled.value = false;
}

const loading = ref(false);

// 禁用当前日期之前日期(不包含当天日期)
const disabledDate = (time: Date) => {
  if (time.getTime() > dayjs(props.endDate).valueOf()) {
    return true;
  }
  if (time.getTime() < dayjs(props.beginDate).valueOf()) {
    return true;
  }
  return false;
};

/** 订货计划保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      formData.demandId = formData.demandId ? formData.demandId : props.id;
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url:
          props.id != ""
            ? "/srm/srmdemandschedule/add"
            : "/srm/srmdemandschedule/modify",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
// 删除单元格数据
const loadingDelete = ref(false);
async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除该数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loadingDelete.value = true;
    await request({
      url: `/srm/srmdemandschedule/remove/${id}`,
      method: "get",
    })
      .then((res) => {
        ElMessage.success("删除成功！");
        closeDialog();
        emit("reset-table", formData.id);
      })
      .finally(() => {
        loadingDelete.value = false;
      });
  });
}

onMounted(() => {});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
